package com.xuecheng.order.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CoursePubVo;
import com.xuecheng.commons.model.vo.OrdersVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoThreadLocal;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.commons.utils.MoneyTransfer;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.learning.api.LearningClient;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mappers.OrdersMapper;
import com.xuecheng.order.mappers.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.order.utils.PayUtils;
import com.xuecheng.web.exceptions.BusinessException;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author 七安
 * @since 2022-09-30
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ContentClient contentClient;

    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private PayUtils payUtils;

    @Autowired
    private LearningClient learningClient;

    /**
     * 创建订单
     *
     * @param coursePubId 课程发布id
     * @return 结果
     */
    @Override
    public ResponseResult<String> createOrder(Long coursePubId) throws BusinessException {
        //判空
        if (coursePubId == null) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //根据课程发布id和学生id查询订单
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getCoursePubId, coursePubId);
        wrapper.eq(Orders::getUserId, AuthInfoThreadLocal.getUserId());
        wrapper.eq(Orders::getStatus, OrdersConstants.ORDER_PAID_STATUS);
        Orders orders = ordersMapper.selectOne(wrapper);
        //如果当前课程的订单已经支付
        if (ObjectUtils.isNotEmpty(orders)) {
            throw new BusinessException(ErrorCode.ORDERERROR);
        }
        //查询是否有待支付的订单
        LambdaQueryWrapper<Orders> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Orders::getCoursePubId, coursePubId);
        wrapper1.eq(Orders::getUserId, AuthInfoThreadLocal.getUserId());
        wrapper1.eq(Orders::getStatus, OrdersConstants.ORDER_INIT_STATUS);
        orders = ordersMapper.selectOne(wrapper1);
        //不为空直接返回订单编号
        if (ObjectUtils.isNotEmpty(orders)) {
            return ResponseResult.okResult(orders.getOrderNo());
        }
        //创建订单
        orders = new Orders();
        ResponseResult<CoursePubVo> responseResult = contentClient.findById(coursePubId);
        if (ErrorCode.SUCCESS.getCode() != responseResult.getCode()) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        CoursePubVo coursePubVo = responseResult.getData();
        //设置订单编号
        orders.setOrderNo(UUID.randomUUID().toString(true));
        //设置课程发布id
        orders.setCoursePubId(coursePubId);
        //设置课程发布名称
        orders.setCoursePubName(coursePubVo.getName());
        //设置机构id
        orders.setCompanyId(coursePubVo.getCompanyId());
        //设置机构名称
        orders.setCoursePubName(coursePubVo.getCompanyName());
        //设置用户id
        orders.setUserId(AuthInfoThreadLocal.getUserId());
        //设置价格(单位是分)
        String priceStr = MoneyTransfer.changeY2F(coursePubVo.getPrice().doubleValue());
        orders.setPrice(new BigDecimal(priceStr));
        //设置订单状态
        orders.setStatus(OrdersConstants.ORDER_INIT_STATUS);
        //添加到数据库
        ordersMapper.insert(orders);
        return ResponseResult.okResult(orders.getOrderNo());
    }

    /**
     * 查询支付结果
     *
     * @param orderNo 查询支付结果
     * @return 订单信息
     */
    @GlobalTransactional
    @Override
    public ResponseResult<OrdersVo> findPayResult(String orderNo) throws BusinessException {
        //判断传来的参数
        if (StringUtils.isEmpty(orderNo)) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //根据订单号查询订单
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getOrderNo, orderNo);
        Orders orders = ordersMapper.selectOne(wrapper);
        //判空
        if (ObjectUtils.isEmpty(orderNo) || !orders.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        //查询是否支付成功
        //todo 等上线在开启付费 Boolean result = payUtils.checkPayment(orderNo);
        Boolean result = true;
        if (result) {
            //更新支付状态
            orders.setStatus(OrdersConstants.ORDER_PAID_STATUS);
            ordersMapper.updateById(orders);
            //更新支付信息
            LambdaQueryWrapper<Payment> paymentWrapper = new LambdaQueryWrapper<>();
            paymentWrapper.eq(Payment::getOrderNo, orderNo);
            Payment payment = paymentMapper.selectOne(paymentWrapper);
            payment.setStatus(OrdersConstants.PAID.toString());
            payment.setPayDate(new Date());
            paymentMapper.updateById(payment);
            //跟新选课计划
            learningClient.saveOrUpdateCourseRec(orders.getCoursePubId(), orders.getUserId());
        }
        OrdersVo ordersVo = BeanHelper.copyProperties(orders, OrdersVo.class);
        return ResponseResult.okResult(ordersVo);
    }
}
